package plus.feifei.attack.controller;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class TestController {
    @PostMapping("/orc")
    public String performOCR1(@RequestParam("file") MultipartFile file) throws TesseractException, IOException {
        Tesseract tesseract = new Tesseract();
        tesseract.setDatapath("/usr/share/tesseract/");
//        tesseract.setLanguage("chi_sim+eng");


        BufferedImage image = ImageIO.read(file.getInputStream());

        // 遍历图片的每个像素点，将其转化为黑白
        int width = image.getWidth();
        int height = image.getHeight();

        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                Color color = new Color(image.getRGB(i, j));
                int gray = (int) (color.getRed() * 0.299 + color.getGreen() * 0.587 + color.getBlue() * 0.114);
                result.setRGB(i, j, new Color(gray, gray, gray).getRGB());
            }
        }

        String txt = tesseract.doOCR(image);
        return txt;
    }
}
